package com.googlecode.alfrescocachingserver.web;

import java.lang.management.ManagementFactory;
import java.util.List;

import javax.management.MBeanServer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.management.ManagementService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CacheServletContextListener implements ServletContextListener
{
    private static final Logger LOG = LoggerFactory.getLogger(CacheServletContextListener.class);

    private ManagementService managementService;

    /**
     * Notification that the web application initialization process is starting.
     * All ServletContextListeners are notified of context initialization before
     * any filter or servlet in the web application is initialized.
     */
    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
        System.setProperty("com.sun.management.jmxremote", "");
        LOG.info("Starting JMS MBeanServer");
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        managementService = new ManagementService(CacheManager.getInstance(), mBeanServer, true, true, true, true, true);
        managementService.init();
    }

    /**
     * Notification that the servlet context is about to be shut down. All
     * servlets and filters have been destroyed before any
     * ServletContextListeners are notified of context destruction.
     * <p/>
     * Shuts down all cache managers known to
     * {@link CacheManager#ALL_CACHE_MANAGERS}
     */
    public void contextDestroyed(ServletContextEvent servletContextEvent)
    {
        // shutdown management service
        try
        {
            managementService.dispose();
        }
        catch (CacheException e)
        {
            LOG.error(e.getMessage(), e);
        }
        LOG.info("Shutting down Ehcache.");

        // shutdown cache managers
        List<CacheManager> knownCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
        if (LOG.isDebugEnabled())
        {
            LOG.debug("Shutting down " + knownCacheManagers.size() + " CacheManagers.");
        }
        
        while (!knownCacheManagers.isEmpty())
        {
            CacheManager.ALL_CACHE_MANAGERS.get(0).shutdown();
        }
    }
}